package com.ijunfu.detail.callable;

import lombok.extern.slf4j.Slf4j;

import java.util.OptionalInt;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.stream.IntStream;

/**
 *
 * @Title  : 求100以内的累加值
 * @Author : ijunfu <ijunfu@163.com>
 * @Date   : 2023/11/23 22:12
 * @Version: 1.0
 * @Motto  : 世界很大 世界很小
 *
 */
@Slf4j
public class _01Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. 创建Callable实现类
        class Task implements Callable<Integer> {
            private Integer num;
            public Task(Integer num) {
                this.num = num;
            }
            @Override
            public Integer call() throws Exception {

                if(num < 1 || num > 100) {
                    return -1;
                }

                return IntStream.range(1, num + 1).reduce((a, b) -> a + b).getAsInt();
            }
        }

        // 2. 创建Callable实现类的实例
        Task calcTask = new Task(100);

        // 3. 使用FutureTask包装Callable实现类的实例
        FutureTask<Integer> futureTask = new FutureTask<>(calcTask);

        // 4. 使用FutureTask作为Thread对象的参数创建线程,并启动
        Thread t = new Thread(futureTask);
        t.start();

        // 5. 调用FutureTask的get方法获取Callable实现类的返回值
        Integer result = futureTask.get();
        log.info("result={}", result);

    }
}
